from django.http.response import HttpResponse
from django.shortcuts import redirect, render
from UserMgr.models import Script
import os
import paramiko


# Create your views here.

def showscript(request):
    res_list=Script.objects.all()
    return render(request,'scriptlist.html',locals())

def runscript(request):
    res_list=Script.objects.all()
    return render(request,'runscript.html',locals())

def runnow(request):
    # return redirect('http://www.baidu.com')
    if request.method=='POST':
        ip=request.POST.get('ip')
        scontent=request.POST.get('scontent')
        content=scontent
        result=ssh(ip,scontent)
        # result=fab_local()
        # result=fab_run(ip,content)
        return render(request,'runscript.html',locals())

def ssh(ip,content):
    ssh = paramiko.SSHClient()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())    #指定当对方主机没有本机公钥的情况时应该怎么办，AutoAddPolicy表示自动在对方主机保存下本机的秘钥
    ssh.connect(ip,22,'root','Just4fun')    #SSH端口默认22，可改
    stdin,stdout,stderr = ssh.exec_command(content)    #这三个得到的都是类文件对象
    outmsg,errmsg = stdout.read(),stderr.read()    #读一次之后，stdout和stderr里就没有内容了，所以一定要用变量把它们带的信息给保存下来，否则read一次之后就没有了
    print(outmsg.decode())
    if errmsg.decode() != "":
        print(errmsg.decode())
    ssh.close()
    return outmsg.decode()
    # return outmsg.decode().replace('\n','<br>')

#方法1：写好执行脚本，本地调用
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
#print("==============="+os.path.join(BASE_DIR,"ScriptMgr","fabconfig.py"))
#print(os.popen("fab -f "+os.path.join(BASE_DIR,"ScriptMgr","fabconfig.py")+" hostname").read())
def fab_local():
    return(os.popen("fab -f "+os.path.join(BASE_DIR,"ScriptMgr","fabconfig.py")+" hostname").read())

#方法2：从前端接收命令，然后调用
#cmd="fab -H 49.234.187.88 --port 22 --user=root --password=Just4fun -- df -h"
#print(os.popen(cmd).read())
def fab_run(ip,cmd):
    return(os.popen("fab -H "+ip+" --port 22 --user=root --password=Just4fun -- "+cmd).read())
